﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfSnqkGasAnalysis.Common;
using WpfSnqkGasAnalysis.IBusiness_impl;
using WpfSnqkGasAnalysis.IData;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis
{
    /// <summary>
    /// 气分析，审核页面。
    /// WindowGasCheck.xaml 的交互逻辑
    /// </summary>
    /// 创建时间：2022-12-9 16:56:58。作者：王浩力
    public partial class WindowGasCheck : Window
    {
        public WindowGasCheck()
        {
            InitializeComponent();
        }

        const string rejectTishi = "请输入驳回理由";

        /// <summary>
        /// 被审核的数据
        /// </summary>
        /// 创建时间：2022-12-10 15:50:15。作者：王浩力
        public Gas_analysis gas_Analysis = null;

        UserBusiness userBusiness = new UserBusiness();

        //下拉框数据初始化。创建时间：2022-12-6 14:23:37。作者：王浩力
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ISource_dictDAL source_DictDAL = ServicesHelpter.GetService<ISource_dictDAL>();
            var all = source_DictDAL.GetAll();
            all = all.Where(g => g.D_stat == 1).ToList();

            //类别下拉框
            cmb_cate.ItemsSource = all.Where(g => g.Group_id.Equals("cate")).ToList();
            cmb_cate.DisplayMemberPath = "Item_name";
            cmb_cate.SelectedValuePath = "Id";

            //构造名称
            cmb_gouzao.ItemsSource = all.Where(g => g.Group_id.Equals("structure")).ToList();
            cmb_gouzao.DisplayMemberPath = "Item_name";
            cmb_gouzao.SelectedValuePath = "Id";

            //顶界层位
            cmb_topCeng.ItemsSource = all.Where(g => g.Group_id.Equals("cengwei")).ToList();

            //底界层位
            cmb_bottomCeng.ItemsSource = all.Where(g => g.Group_id.Equals("cengwei")).ToList();

            //取样位置
            cmb_quyang.ItemsSource = all.Where(g => g.Group_id.Equals("quyangLocation")).ToList();
            cmb_quyang.DisplayMemberPath = "Item_name";
            cmb_quyang.SelectedValuePath = "Id";

            //取样单位
            cmb_samping_company_name.ItemsSource = all.Where(g => g.Group_id.Equals("quyang")).ToList();
            cmb_samping_company_name.DisplayMemberPath = "Item_name";
            cmb_samping_company_name.SelectedValuePath = "Id";

            //分析单位
            cmb_analysis_company_name.ItemsSource = all.Where(g => g.Group_id.Equals("quyang")).ToList();
            cmb_analysis_company_name.DisplayMemberPath = "Item_name";
            cmb_analysis_company_name.SelectedValuePath = "Id";

            //取样条件
            cmb_samping_condition.ItemsSource = all.Where(g => g.Group_id.Equals("quyangCondition")).ToList();
            cmb_samping_condition.DisplayMemberPath = "Item_name";
            cmb_samping_condition.SelectedValuePath = "Id";

            //委托单位
            cmb_client.ItemsSource = all.Where(g => g.Group_id.Equals("quyang")).ToList();
            cmb_client.DisplayMemberPath = "Item_name";
            cmb_client.SelectedValuePath = "Id";

            //取样人
            var userList = userBusiness.GetAllUser();
            samping_user.ItemsSource = userList;
            samping_user.DisplayMemberPath = "User_real_name";
            samping_user.SelectedValuePath = "Id";

            //分析人
            analysis_user.ItemsSource = userList;
            analysis_user.DisplayMemberPath = "User_real_name";
            analysis_user.SelectedValuePath = "Id";

            //设置所有输入控件只读
            #region 设置所有输入控件只读
            var grid = (DependencyObject)this.Content;
            List<DependencyObject> list = new List<DependencyObject>();
            Action<DependencyObject> action = null;
            action = (a) =>
            {
                var count = VisualTreeHelper.GetChildrenCount(a);
                for (int i = 0; i < count; i++)
                {
                    var elem = VisualTreeHelper.GetChild(a, i);
                    list.Add(elem);
                    action(elem);
                }
            };

            action(grid);

            foreach (var item in list)
            {
                if (item is TextBox)
                {
                    var elem = (item as TextBox);
                    if (elem.Name.Equals("txtRejectReason"))
                    {
                        continue;
                    }
                    (item as TextBox).IsEnabled = false; //批量设置输入框禁用
                }
                else if (item is ComboBox)
                {
                    (item as ComboBox).IsEnabled = false;
                }
            }

            #endregion

            //读取已经录入的数据，给校对人。添加时间：2022-12-8 22:55:57
            Task.Run(() =>
            {
                //查询校对的数据
                Gas_analysisBusiness gas_AnalysisBusiness = new Gas_analysisBusiness();
                var info = gas_AnalysisBusiness.Get(gas_Analysis.Id);

                this.Dispatcher.InvokeAsync(() =>
                {
                    HE.Text = info.He.ToKeepDecimal(4);
                    H2.Text = info.H2.ToKeepDecimal(4);
                    O2.Text = info.O2.ToKeepDecimal(4);
                    N2.Text = info.N2.ToKeepDecimal(4);
                    C1.Text = info.C1.ToKeepDecimal(4);
                    C6.Text = info.C6.ToKeepDecimal(4);
                    C3.Text = info.C3.ToKeepDecimal(4);
                    IC4.Text = info.Ic4.ToKeepDecimal(4);
                    NC4.Text = info.Nc4.ToKeepDecimal(4);
                    IC5.Text = info.Ic5.ToKeepDecimal(4);
                    NC5.Text = info.Nc5.ToKeepDecimal(4);
                    CO2.Text = info.CO2.ToKeepDecimal(4);
                    C2.Text = info.C2.ToKeepDecimal(4);
                    txt_totalSum.Text = info.All_calc_value.ToKeepDecimal(4);

                    txtYpbh.Text = info.Sample_no;
                    txtJh.Text = info.Well_no;
                    top_well_deep.Text = info.Top_well_deep.ToString();
                    bottom_well_deep.Text = info.Bottom_well_deep.ToString();
                    remark.Text = info.Remark;

                    //取样温度
                    samping_temperature.Text = info.Samping_temperature.ToString();

                    //oil_pressure.Text = info.Oil_pressure.ToString();
                    //casing_pressure.Text = info.Casing_pressure.ToString();

                    //油压，套压保留两位小数  //修改时间：2023-2-7 14:13:05。作者：王浩力
                    if (info.Oil_pressure.HasValue)
                    {
                        oil_pressure.Text = info.Oil_pressure.Value.ToString("F2");
                    }
                    if (info.Casing_pressure.HasValue)
                    {
                        casing_pressure.Text = info.Casing_pressure.Value.ToString("F2");
                    }

                    zong_s.Text = info.Zong_s.ToString();
                    water_point.Text = info.Water_point.ToString();

                    //取样时间             
                    DateTime samping_timeShow;
                    DateTime.TryParse(info.Samping_time, out samping_timeShow);
                    dateQuyangTime.SelectedDateTime = samping_timeShow;

                    //分析时间
                    DateTime analysis_timeShow;
                    DateTime.TryParse(info.Analysis_time, out analysis_timeShow);
                    analysis_time.SelectedDateTime = analysis_timeShow;

                    txtH2S_input.Text = info.H2Smg.ToString();

                    //下拉框赋值
                    cmb_cate.SelectedValue = info.Cate;
                    cmb_gouzao.SelectedValue = info.Build_name;
                    cmb_topCeng.SelectedValue = info.Top_horizon;
                    cmb_bottomCeng.SelectedValue = info.Bottom_horizon;

                    //cmb_quyang.SelectedValue = info.Sampling_location;
                    //取样位置。//修改时间：2023-1-15 15:45:25
                    if (Regex.IsMatch(info.Sampling_location, "^\\d{19}"))
                    {
                        cmb_quyang.SelectedValue = info.Sampling_location;
                    }
                    else
                    {
                        txt_quyang.IsEnabled = false;
                        txt_quyang.Text = info.Sampling_location;
                    }

                    cmb_samping_company_name.SelectedValue = info.Samping_company_name;
                    cmb_analysis_company_name.SelectedValue = info.Analysis_company_name;

                    cmb_samping_condition.SelectedValue = info.Samping_condition;
                    cmb_client.SelectedValue = info.Client;
                    samping_user.SelectedValue = info.Samping_user_id;
                    analysis_user.SelectedValue = info.Analysis_user_id;//分析人
                });
            });
        }

        //预览打印报告
        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        //驳回。//创建时间：2022-12-9 23:17:13。作者：王浩力
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtRejectReason.Text) || txtRejectReason.Text.Trim().Equals(rejectTishi))
            {
                ShowAlertHelpter.ShowAlert(rejectTishi);
                return;
            }
            Gas_analysisBusiness gas_AnalysisBusiness = new Gas_analysisBusiness();
            gas_Analysis.O_step = 3;
            gas_Analysis.E3 = txtRejectReason.Text;
            var result = gas_AnalysisBusiness.CheckGas(gas_Analysis);
            if (result.CodeEnum == ResultCode.Success)
            {
                btnPass.IsEnabled = false;
                btnReject.IsEnabled = false;
            }
            ShowAlertHelpter.ShowAlert(result.Msg);
        }

        private void C2_KeyUp(object sender, KeyEventArgs e)
        {
            //CalcTotalValue();
        }

        //检查输入字符串是否为数字 //创建时间：2022-12-7 15:16:20，作者：王浩力
        private void samping_temperature_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            var textElem = (sender as TextBox);

            //解决连续输入很多.
            if ((
                textElem.Text.StartsWith(".") || string.IsNullOrWhiteSpace(textElem.Text)
                || textElem.Text.Contains(".")
                ) && e.Text == ".")
            {
                e.Handled = true;
                return;
            }

            //禁止在0前面继续输入0
            int index = ((System.Windows.Controls.TextBox)e.Source).CaretIndex;
            if (textElem.Text.StartsWith("0.") && index == 0 && e.Text == "0")
            {
                e.Handled = true;
                return;
            }

            //不能输入非数字
            if (Regex.IsMatch(e.Text, @"[^\d+\.{0,1}\d+]+"))
            {
                e.Handled = true;
                return;
            }
        }

        //检查输入字符串是否为数字 //创建时间：2022-12-7 15:16:20，作者：王浩力
        private void samping_temperature_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (!string.IsNullOrWhiteSpace(textBox.Text))
            {
                if (textBox.Text == "0.0" || textBox.Text.StartsWith("00"))
                {
                    textBox.Text = textBox.Text.Replace("00", "");
                }
                if (!textBox.Text.StartsWith("0.") && Regex.IsMatch(textBox.Text, @"0+[1-9]+\.*\d+", RegexOptions.IgnoreCase))
                {
                    textBox.Text = textBox.Text.TrimStart('0');
                }

                //输入的不是小数或正整数           
                Regex regex = new Regex(@"[^\d+\.{0,1}\d+]", RegexOptions.IgnoreCase);
                textBox.Text = regex.Replace(textBox.Text, "");
            }
        }

        //退出  //创建时间：2022-12-8 18:06:28。作者：王浩力
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {

            this.Close();
        }

        //驳回控件获取输入焦点时触发。创建时间：2022-12-10 14:09:34。
        private void txtRejectReason_GotFocus(object sender, RoutedEventArgs e)
        {
            //ShowAlertHelpter.ShowAlert("输入焦点");
            if (txtRejectReason.Text.Equals("请输入驳回理由"))
            {
                txtRejectReason.Text = "";
            }
        }

        //审核通过处理         //创建时间：2022-12-10 15:51:01。作者：王浩力
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            Gas_analysisBusiness gas_AnalysisBusiness = new Gas_analysisBusiness();
            gas_Analysis.O_step = 4;
            var result = gas_AnalysisBusiness.CheckGas(gas_Analysis);
            if (result.CodeEnum == ResultCode.Success)
            {
                //审核通过的，生成PDF文件 //创建时间：2023-1-11 17:07:51
                //查询完整数据
                Gas_analysisBusiness busi = new Gas_analysisBusiness();
                SourceDictBusiness sourceDictBusiness = new SourceDictBusiness();
                var model = busi.GetInfoStr(gas_Analysis.Id);

                //天然气，备注 ，标准。创建时间：2023-1-11 14:42:34，作者：王浩力
                var biaozhunList = sourceDictBusiness.GetListByGroup("gas_bz_remark_list", 1);
                biaozhunList = biaozhunList.OrderBy(g => g.Createtime).ToList();
                model.source_Dicts = biaozhunList;
                string pdfFileName = $"天然气{gas_Analysis.Sample_no}{gas_Analysis.Well_no}";
                MakePdfHelpter.CheckPassLoadXps(pdfFileName, "DocumentGasPrint.xaml", model, 
                    () => {
                        //天然气每月大概一百多个文件，每月一个文件夹
                        string dir = DateTime.Now.ToString("yyyy_MM");
                        dir = System.IO.Path.Combine("天然气", dir);
                        return dir;
                });

                btnPass.IsEnabled = false;
                btnReject.IsEnabled = false;
            }
            ShowAlertHelpter.ShowAlert(result.Msg);
        }
    }
}
